package com.apobates.jforum2.troll.accounts.biz.impl;

import com.apobates.jforum2.troll.accounts.biz.MemberNamesProtectService;
import com.apobates.jforum2.troll.accounts.biz.dao.MemberNamesProtectDao;
import com.apobates.jforum2.troll.accounts.entity.MemberNamesProtect;
import java.util.Optional;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 *
 * @author xiaofanku
 * @since 20200515
 */
@Service
public class MemberNamesProtectServiceImpl implements MemberNamesProtectService{
    @Autowired
    private MemberNamesProtectDao memberNamesProtectDao;
    private final static Logger logger = LoggerFactory.getLogger(MemberNamesProtectServiceImpl.class);
    
    @Override
    public Stream<MemberNamesProtect> getAll() {
        return memberNamesProtectDao.findAll();
    }
    
    @Override
    public Optional<MemberNamesProtect> get(int id) {
        if (id > 0) {
            return memberNamesProtectDao.findOne(id);
        }
        return Optional.empty();
    }
    
    @Override
    public Optional<MemberNamesProtect> create(String memberNames)throws IllegalArgumentException {
        return build(new MemberNamesProtect(memberNames));
    }
    
    @Override
    public Optional<MemberNamesProtect> create(String memberNames, boolean status)throws IllegalArgumentException {
        MemberNamesProtect mnp = new MemberNamesProtect(memberNames);
        mnp.setStatus(status);
        return build(mnp);
    }
    
    @Override
    public Optional<Boolean> editStatus(int id, boolean status)throws IllegalArgumentException {
        MemberNamesProtect mnp = get(id).orElseThrow(()->new IllegalArgumentException("保护帐号不存在"));
        mnp.setStatus(status);
        return memberNamesProtectDao.edit(mnp);
    }
    
    @Override
    public Optional<Boolean> edit(int id, MemberNamesProtect updateEntity)throws IllegalArgumentException {
        MemberNamesProtect mnp = get(id).orElseThrow(()->new IllegalArgumentException("保护帐号不存在"));
        mnp.setStatus(updateEntity.isStatus());
        mnp.setMemberNames(updateEntity.getMemberNames());
        return memberNamesProtectDao.edit(mnp);
    }
    private Optional<MemberNamesProtect> build(MemberNamesProtect namesProtect)throws IllegalArgumentException{
        //内置的不需要创建
        if(MemberNamesProtect.getNativeProtect().contains(namesProtect.getMemberNames())){
            throw new IllegalArgumentException("内置保护的帐号不需要创建");
        }
        try {
            memberNamesProtectDao.save(namesProtect);
            return Optional.of(namesProtect);
        } catch (Exception e) {
            if(logger.isDebugEnabled()){
                logger.debug("创建会员帐号保护失败", e);
            }
        }
        return Optional.empty();
    }
}